package com.sjs.boot.dynamic.core.run.request;

import com.sjs.boot.dynamic.core.run.MethodContext;
import com.sjs.boot.dynamic.protocol.RetCode;
import com.sjs.boot.dynamic.util.JsonUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Map;

/**
 * @author uto_dev_008
 * @desc
 * @since 2021/11/30 13:48
 * Copyright (c) 2021 南京友拓信息技术有限公司 All rights reserved
 */
public class JsonRequester extends RestRequester{
    private static final String METHOD_POST = "POST";
    private static final Logger LOG = LoggerFactory.getLogger(JsonRequester.class);

    @Override
    public int buildParas(MethodContext context, Map<String, Object> reqParameters) {
        int retCode = super.buildParas(context, reqParameters);
        if(retCode != RetCode.OK.getCode()) {
            return retCode;
        }

        HttpServletRequest req = context.getRequest();
        if(!METHOD_POST.equals(req.getMethod())) { //兼容配置错误，非post方式，无消息体
            return RetCode.OK.getCode();
        }

        Map<String, Object> para = null;
        try {
            /**
             * 消息体加密了，使用azdg算法，contentType为二进制
             * 必须携带了通行证，且通行证不在消息体中，否则没有密码可以解密
             */
            para = JsonUtil.jsonStreamToMap(req.getInputStream());

            if(para != null) {
                reqParameters.putAll(para);
            } else {
                LOG.warn("Fail to read json data from input stream in {}", context.getMethodConfig().getName());
            }
            return RetCode.OK.getCode();
        } catch (IOException e) {
            LOG.warn("Fail to read json data from input stream in {}", context.getMethodConfig().getName());
            return RetCode.WRONG_PARAMETER.getCode();
        }
    }
}
